import { memo, useCallback, useEffect, useState } from 'react';
import { Table, Card, Button, Modal, Form, Input, Avatar, Space, Popconfirm, Tag } from 'antd';
import { UserOutlined, PlusOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { addUserApi, deleteUserApi, getUserListApi, UserList } from '@/api/adminApi';
import dayjs from 'dayjs';
import useApp from 'antd/es/app/useApp';

const User = () => {
  const [form] = Form.useForm();
  const [userList, setUserList] = useState<UserList[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [searchValue, setSearchValue] = useState('');
  const app = useApp();

  // 获取用户列表
  const getUserList = useCallback(async () => {
    try {
      setLoading(true);
      const res = await getUserListApi();
      if (res.code === 200) {
        setUserList(res.data as unknown as UserList[]);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
      app.message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  }, [app]);

  // 新增用户
  const handleAddUser = async () => {
    try {
      const values = await form.validateFields();
      const res = await addUserApi(values);
      if (res.code === 200) {
        app.message.success('添加用户成功');
        setIsModalOpen(false);
        form.resetFields();
        getUserList(); // 重新获取用户列表
      }
    } catch (error) {
      console.error('添加用户失败:', error);
      app.message.error('添加用户失败');
    }
  };

  // 删除用户
  const handleDeleteUser = async (id: string) => {
    try {
      const res = await deleteUserApi(id);
      if (res.code === 200) {
        app.message.success('删除用户成功');
        getUserList(); // 重新获取用户列表
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      app.message.error('删除用户失败');
    }
  };

  // 显示新增用户弹窗
  const showModal = () => {
    form.resetFields();
    setIsModalOpen(true);
  };

  // 关闭新增用户弹窗
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 过滤用户
  const filteredUsers = userList.filter(
    (user) =>
      user.username.toLowerCase().includes(searchValue.toLowerCase()) ||
      user.phone.includes(searchValue)
  );

  // 表格列配置
  const columns = [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      render: (text: string) => <span className="text-gray-500">{text}</span>,
    },
    {
      title: '用户头像',
      dataIndex: 'avatar',
      key: 'avatar',
      width: 80,
      render: (avatar: string) => (
        <Avatar
          src={avatar}
          icon={!avatar && <UserOutlined />}
          size="large"
          className="border border-gray-200"
        />
      ),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      render: (text: string) => <span className="font-medium">{text}</span>,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '注册时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '最后更新',
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: UserList) => (
        <Space size="middle">
          <Popconfirm
            title="确定要删除此用户吗?"
            description="此操作不可恢复，用户所有数据将被删除"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确定"
            cancelText="取消"
            okButtonProps={{ danger: true }}
          >
            <Button
              type="text"
              danger
              icon={<DeleteOutlined />}
              size="small"
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    getUserList();
  }, [getUserList]);

  return (
    <div className="user-management p-4">
      <Card
        title={
          <div className="flex items-center">
            <UserOutlined className="mr-2 text-purple-600" />
            <span>用户管理</span>
          </div>
        }
        extra={
          <Space>
            {/* 搜索框 */}
            <Input
              placeholder="搜索用户名或手机号"
              value={searchValue}
              onChange={(e) => setSearchValue(e.target.value)}
              prefix={<SearchOutlined className="text-gray-400" />}
              allowClear
              style={{ width: 220 }}
            />
            {/* 新增用户按钮 */}
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={showModal}
              style={{ backgroundColor: '#7D33FF' }}
            >
              新增用户
            </Button>
          </Space>
        }
        className="shadow-sm"
      >
        {/* 用户统计信息 */}
        <div className="mb-4 flex gap-4">
          <Tag
            color="blue"
            className="px-3 py-1 text-sm"
          >
            用户总数: {userList.length}
          </Tag>
          <Tag
            color="green"
            className="px-3 py-1 text-sm"
          >
            当前显示: {filteredUsers.length}
          </Tag>
        </div>

        {/* 用户列表 */}
        <Table
          dataSource={filteredUsers}
          columns={columns}
          rowKey="id"
          loading={loading}
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            showTotal: (total) => `共 ${total} 条数据`,
          }}
          bordered
          size="middle"
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 新增用户弹窗 */}
      <Modal
        title={
          <div className="flex items-center">
            <PlusOutlined className="mr-2 text-purple-600" />
            <span>新增用户</span>
          </div>
        }
        open={isModalOpen}
        onOk={handleAddUser}
        onCancel={handleCancel}
        okText="确认添加"
        cancelText="取消"
        okButtonProps={{ style: { backgroundColor: '#7D33FF' } }}
      >
        <Form
          form={form}
          layout="vertical"
          name="addUserForm"
          initialValues={{ remember: true }}
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input
              prefix={<UserOutlined className="text-gray-400" />}
              placeholder="请输入用户名"
            />
          </Form.Item>

          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入有效的手机号码',
              },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, message: '密码长度不能少于6位' },
            ]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default memo(User);
